package com.sdy.mvc.utils;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>File: CookieUtil.java</p>
 * <p>Description: CookieUtil</p>
 *
 * @author zzq
 * @version V1.0
 * @since 2019-05-09
 */
public class CookieUtil {
    public static String getCookie(HttpServletRequest request, String key) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for(Cookie cookie : cookies) {
                if (StringUtils.equals(cookie.getName(), key)) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    public static void setCookie(HttpServletResponse response, String key, String value, Boolean httpOnly, String domain) {
        Cookie cookie = new Cookie(key,value);
        cookie.setMaxAge(-1);
        cookie.setPath("/");
        cookie.setHttpOnly(httpOnly);
        cookie.setDomain(domain);
        response.addCookie(cookie);
    }
    
    public static void setCookie(HttpServletResponse response, String key, String value, Boolean httpOnly) {
        Cookie cookie = new Cookie(key,value);
        cookie.setMaxAge(-1);
        cookie.setPath("/");
        cookie.setHttpOnly(httpOnly);
        response.addCookie(cookie);
    }
}
